package cn.credit.loan.controller;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.credit.loan.entity.Approve;
import cn.credit.loan.entity.Customer;
import cn.credit.loan.entity.Loanapplication;
import cn.credit.loan.entity.Purpose;
import cn.credit.loan.entity.Staging;
import cn.credit.loan.service.approve.ApproveService;
import cn.credit.loan.service.customer.CustomerService;
import cn.credit.loan.service.loanapplication.LoanapplicationService;
import cn.credit.loan.service.purpose.PurposeService;
import cn.credit.loan.service.staging.StagingService;

@Controller
public class LoanapplicationController {
	private static Logger logger =Logger.getLogger(LoanapplicationController.class);
	
	//注入申请贷款
	@Autowired
	private LoanapplicationService loanapplicationService;
	//注入客户基本信息
	@Autowired
	private CustomerService customerService;
	//注入贷款用途类型
	@Autowired
	private PurposeService purposeService;
	//注入分期期数
	@Autowired
	private StagingService stagingService;
	//注入审批信息
	@Autowired
	private ApproveService approveService;
	/**
	 * 跳转客户申请贷款信息页面
	 * @param session
	 * @return
	 */
	@RequestMapping(value="/loanap")
	public String loanaply(HttpSession session){
		//客户基本信息集合
		List<Customer> custlist=null;
		//贷款用途类型集合
		List<Purpose> purposelist=null;
		//分期期数集合
		List<Staging> stagings=null;
		try {
			//客户基本信息
			custlist = customerService.getCustomerList(null);
			//贷款用途类型
			purposelist=purposeService.getPurpose();
			//分期期数
			stagings= stagingService.Staginglist();
			session.setAttribute("stagings", stagings);
			session.setAttribute("customerList", custlist);
			session.setAttribute("purposelist", purposelist);
		} catch (Exception e) {
			e.printStackTrace();
			return "after/loanapply";
		}
		
		logger.info("#####-------申请贷款页面");
		return "after/loanapply";
	}
	
	/**
	 * 绑定贷款类型到下拉框中（前台）
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/userloanapper")
	public ModelAndView loanapp(Model model){
		logger.info("####--------->> 客户提交贷款信息页面");
		//贷款用途类型集合
		List<Purpose> purposelist=null;
		//分期期数集合
		List<Staging> staginglist=null;
		try {
			//贷款用途类型
			purposelist=purposeService.getPurpose();
			//分期期数
			staginglist= stagingService.Staginglist();
			
			model.addAttribute("purposelist", purposelist);
			model.addAttribute("staginglist", staginglist);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new ModelAndView("front/loanapplication");
	}
	
	/**
	 * 所有贷款信息列表
	 * @param loanapplication
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@RequestMapping(value="/loanapplist")
	@ResponseBody
	public Object LoanAppList(Loanapplication loanapplication,
			@RequestParam(value="pageNum",defaultValue="1",required=false)Integer pageNum,
			@RequestParam(value="pageSize" ,defaultValue="10",required=false)Integer pageSize){
		logger.info("####------->> 进入客户贷款申请列表");
		Map<String, Object> result=new HashMap<String,Object>();
		List<Loanapplication> loanlist=null;
		try {
			PageHelper.startPage(pageNum, pageSize);
			loanlist = loanapplicationService.getLoanAppLicationList(loanapplication);
			PageInfo<Loanapplication> pageInfo=new PageInfo<Loanapplication>(loanlist);
			//总页数
			logger.info("####-------->> 总页数 ="+pageInfo.getPages());
			//总条数
			logger.info("####-------->> 总条数 ="+pageInfo.getTotal());
			//下一页
			logger.info("####-------->> 下一页 ="+pageInfo.getNextPage());
			//上一页
			logger.info("####-------->> 上一页 ="+pageInfo.getPrePage());
			//当前页
			logger.info("####-------->> 当前页 ="+pageInfo.getPageNum());
			//第一页
			logger.info("####-------->> 第一页 ="+pageInfo.getFirstPage());
			//最后一页
			logger.info("####-------->> 最后一页 ="+pageInfo.getLastPage());
			//每页显示条数
			logger.info("####-------->> 每页显示条数 ="+pageInfo.getPageSize());
			//获取当前页信息
			logger.info("####-------->> 获取当前页信息 ="+pageInfo.getStartRow());
			//分页后返回页面的数据
			logger.info("####-------->> 分页后返回页面的数据 ="+pageInfo.getList());
			result.put("loanlist", loanlist);
			result.put("pageinfo", pageInfo);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return JSONArray.toJSONString(result);
	}
	
	/**
	 * 添加客户申请贷款信息(前台)
	 * @param loanapplication
	 * @return
	 */
	@RequestMapping(value="/addloanapp",method=RequestMethod.POST)
	@ResponseBody
	public Object addloans(Loanapplication loanapplication,@RequestParam(value="custName")String custName,
							HttpSession session,HttpServletRequest request,
							@RequestParam(value="attachs",required=false)MultipartFile[] attachs){
		logger.info("####------>> 进入客户提交申请贷款信息");
		String loanCardBackPath=null;//身份证背面
		String loanCardJustPath=null;//身份证正面
		String loanCardPath=null;//手持身份证
		boolean flag=true;
		Map<String, Object> reult=new HashMap<String,Object>();
		String path=request.getSession().getServletContext().getRealPath("static"+File.separator+"uploadfiles");
		for(int i=0;i<attachs.length;i++){
			MultipartFile attach=attachs[i];
			if(!attach.isEmpty()){
				String oldFileName=attach.getOriginalFilename();//原文件名
				String prefix=FilenameUtils.getExtension(oldFileName);//原文件后缀
				int filesize=500000;
				if(attach.getSize()>filesize){//上传文件的不得超过500KB
					reult.put("upload","size");
					flag=false;
				}else if(prefix.equalsIgnoreCase("jpg")
						|| prefix.equalsIgnoreCase("png")
						|| prefix.equalsIgnoreCase("jpeg")
						|| prefix.equalsIgnoreCase("pneg")){//上传图片的格式不正确;
					String fileName=System.currentTimeMillis()+RandomUtils.nextInt(0, 10000)+"_wu.jpg";
					logger.debug("####--------->> "+ fileName);
					try {
						File file=new File(path);
						if(!file.exists()){
							file.mkdirs();
						}
						attach.transferTo(new File(file,fileName));
					} catch (IOException e) {
						reult.put("upload","savefile");
						e.printStackTrace();
						flag=false;
					}
					if(i==0){
						loanCardBackPath=path+File.separator+fileName; 
					}else if(i==1){
						loanCardJustPath=path+File.separator+fileName;
					}else if(i==2){
						loanCardPath=path+File.separator+fileName;
					}
				}else{
					reult.put("upload","prefix");
					flag=false;
				}
			}
		}
		if(flag){
			loanapplication.setLoanDate(new Date());
			loanapplication.setLoanCardBackPath(loanCardBackPath);
			loanapplication.setLoanCardJustPath(loanCardJustPath);
			loanapplication.setLoanCardPath(loanCardPath);
			loanapplication.setLoanType("待审查");
			try {
				Customer customer=new Customer();
				customer.setCustName(loanapplication.getCustName());
				customer.setCustIDcardNo(loanapplication.getCustIDcardNo());
				Customer omer=customerService.getcustomer(customer);
				if(omer!=null){
					loanapplication.setLoancustId(omer.getCustId());
					reult.put("upload", loanapplicationService.addLoanApp(loanapplication));
				}else{
					reult.put("upload", "false");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return JSONArray.toJSONString(reult);
	}
	
	/**
	 * 删除客户申请贷款信息
	 * @param loanId
	 * @param model
	 * @return
	 */
	@RequestMapping("/deleteloanapp")
	public String deleteLoanapp(int loanId,ModelMap model)
	{
		try {
			boolean loanIds=loanapplicationService.deleteLoanapp(loanId);
			if(loanIds)
			{
				model.addAttribute("loanId", loanId);
				return "loanapplicationDelete";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 后台————审查员，对客户申请贷款信息进行审查状态
	 * @param checkId
	 * @param loanId
	 * @param loanType
	 * @return
	 */
	@RequestMapping(value="/updateloanType",method=RequestMethod.POST)
	@ResponseBody
	public Object updateloanType(@RequestParam(value="checkId")Integer checkId,
								 @RequestParam(value="loanId")String loanId,
								 @RequestParam("loanType")String loanType){
		Map<String, Object> reslut=new HashMap<String,Object>();
		try {
			Approve approve=new Approve();
			approve.setCheckId(1);
			approve.setLoanId(Integer.valueOf(loanId));
			approve.setCheckType(loanType);
			approve.setCheckDate(new Date());
			approve.setManagerType("待审批");
			if(approveService.getApproveAdd(approve)){
				reslut.put("upadd", loanapplicationService.updateByLoan(loanId, loanType));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return JSONArray.toJSONString(reslut);
	}
}
